<template>
  <el-form label-width="250px">
    <el-form-item label="SPU名称">
      <el-input
        v-model="ownAttrParams.spuName"
        style="width: 500px"
        placeholder="输入SPU名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="ownAttrParams.tmId" style="width: 350px">
        <el-option
          v-for="item in getSPUBrandListRef"
          :key="item.id"
          :value="item.id as number"
          :label="item.tmName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        v-model="ownAttrParams.description"
        style="width: 500px"
        type="textarea"
        placeholder="输入描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU照片墙">
      <el-upload
        v-model:file-list="photoList"
        action="/app-dev/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog style="margin-top: 100px" v-model="dialogVisible">
        <img
          style="width: 80%; height: 70%"
          :src="dialogImageUrl"
          alt="Preview Image"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性" width="100">
      <el-select
        v-model="noSelectAttr"
        style="width: 350px; margin-right: 20px"
      >
        <el-option
          v-for="item in unSaleValueInselect"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}@@${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        :disabled="noSelectAttr ? false : true"
        @click="addSaleAttr"
        type="primary"
        :icon="Plus"
        >添加销售属性</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-table :data="attributeAndValueList" border>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="saleAttrName"
          label="属性名"
          width="100"
          align="center"
        ></el-table-column>

        <el-table-column label="属性值" align="center" min-width="100">
          <template #="{ row, $index }">
            <el-tag
              @close="row.spuSaleAttrValueList.splice($index, 1)"
              :type="item.id % 2 == 0 ? 'warning' : 'success'"
              closable
              style="margin: 5px 5px"
              v-for="item in row.spuSaleAttrValueList"
              :key="item.id"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              ref="inputHander"
              v-model="attrAddValues"
              @blur="addAttrInput(row)"
              v-if="row.isShow"
              style="width: 100px"
              placeholder="请输入新的属性值"
            ></el-input>
            <el-button
              v-else
              @click="addAttrValueBtn(row)"
              size="small"
              type="primary"
              :icon="Plus"
            ></el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template #="{ row, $index }">
            <el-button
              @click="deleteAttrValue(row, $index)"
              type="danger"
              :icon="Delete"
              circle
            />
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button @click="saveSPU" type="primary">保存</el-button>
      <el-button @click="scene1">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {
  addAndUpdadteSPUProduct,
  getAllSPUAttributeAndValue,
  getSPUAttributeAndValue,
  getSPUBrandList,
  getSPUPhotosList,
} from "@/api/product/spu";
import type {
  AllSPUAttributeList,
  SaleValueType,
  Spu,
  SPUAttributeList,
  SPUAttributeListAPI,
  SPUBrandList,
  SPUImageList,
} from "@/api/product/type/spu";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { computed, nextTick, ref } from "vue";
//场景变为0
const emit = defineEmits(["updateScene"]);
//取消按钮
const scene1 = () => {
  emit("updateScene", {
    val: 0,
    flag: ownAttrParams.value.id ? "更新" : "添加",
    isNobtn: true,
  });
};
//存贮的数据
//SPU所有品牌
const getSPUBrandListRef = ref<SPUBrandList>([]);
//指定照片墙数据
const photoList = ref<any>([]);
//已有的SPU商品销售属性和属性值
const attributeAndValueList = ref<SPUAttributeListAPI>([]);
//全部的SPU商品属性和属性值
const allAttributeAndValueList = ref<AllSPUAttributeList>([]);
//存储没有的销售属性（颜色 版本 尺码）
const noSelectAttr = ref<string>("");
//添加属性值的输入框实例存储
const inputHander = ref();
//存储已有spu数据
const ownAttrParams = ref<Spu>({
  id: "", //SPUid
  description: "", //描述
  spuName: "", //名字
  category3Id: "", //三级分类ID
  tmId: "", //品牌ID
  spuSaleAttrList: [], //没有需要接口获取
  spuImageList: [], //没有需要接口获取
});
//获取四个接口请求，为了满足参数
//存储已有的商品属性数据

//获取接口函数
const getAPI = async (row: Spu) => {
  //合并数据
  Object.assign(ownAttrParams.value, JSON.parse(JSON.stringify(row)));

  // console.log("获取4个请求");
  //参数中的row是已有spu数据，但是不全
  //下面开始调用接口补全数据
  //获取SPU所有品牌数据
  const res1: SPUBrandList = await getSPUBrandList();
  //获取指定照片墙数据
  const res2: SPUImageList = await getSPUPhotosList(row.id as number);
  //已有的SPU销售属性和属性值
  const res3: SPUAttributeListAPI = await getSPUAttributeAndValue(
    row.id as number
  );
  //获取全部SPU销售属性
  const res4: AllSPUAttributeList = await getAllSPUAttributeAndValue();
  //存数据
  getSPUBrandListRef.value = res1;
  //存储upload组件需要的图片数组结构
  photoList.value = res2.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });

  attributeAndValueList.value = res3;
  allAttributeAndValueList.value = res4;
};
//筛选出select中表示的未拥有的商品属性
// attributeAndValueList和allAttributeAndValueList两者比较
const unSaleValueInselect = computed(() => {
  const result = allAttributeAndValueList.value.filter((item) => {
    return attributeAndValueList.value.every((item2: any) => {
      return item2.baseSaleAttrId != item.id && item2.saleAttrName != item.name;
    });
  });

  return result;
});
//添加销售属性按钮
const addSaleAttr = () => {
  //解构未有的销售属性名和id的字符串
  const [baseSaleAttrId, saleAttrName] = noSelectAttr.value.split("@@");

  attributeAndValueList.value.push({
    baseSaleAttrId, //属性id
    saleAttrName, //属性名
    spuSaleAttrValueList: [], //属性值数组
  } as any);
  noSelectAttr.value = "";
};
//放大展示dialog的控制变量
const dialogVisible = ref<boolean>(false);
//存储放大展示的图片地址
const dialogImageUrl = ref<string>("");
//点击已经上传图片的钩子函数
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
//添加属性值按钮
const addAttrValueBtn = (row: SPUAttributeList) => {
  row.isShow = true;
  //输入框出现立刻获取焦点
  //写在响应式数据下面，为了数据变化后能第一时间得到新逻辑
  nextTick(() => {
    inputHander.value.focus();
  });
};
//添加属性值input绑定
const attrAddValues = ref<string>("");
//添加属性值输入框失去焦点函数
const addAttrInput = (row: SPUAttributeList) => {
  row.isShow = false;
  //输入不能重复约束
  if (
    row.spuSaleAttrValueList?.find((item) => {
      return item.saleAttrValueName == attrAddValues.value;
    })
  ) {
    ElMessage({
      type: "error",
      message: "输入值重复",
    });
    attrAddValues.value = "";
    return;
  }
  //输入不能为空约束
  if (attrAddValues.value.trim() == "") {
    ElMessage({
      type: "error",
      message: "输入不能为空",
    });
    return;
  }
  //生成tag标签和提交修改请求需要的对象
  const addAttrObj = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: attrAddValues.value,
  };
  //将新输入的属性值加入到属性值数组
  row.spuSaleAttrValueList?.push(addAttrObj as any);
  //清空输入框
  attrAddValues.value = "";
};
//添加属性值的删除按钮
const deleteAttrValue = (row: any, index: number) => {
  // 接收到的参数index是从0开始的
  //删除数据
  row.spuSaleAttrValueList.splice(index, 1);
};
//保存按钮函数
const saveSPU = async () => {
  //将已有的销售属性和属性值复制给请求需要的传参对象
  ownAttrParams.value.spuSaleAttrList = attributeAndValueList.value;
  //将照片墙的数据格式化
  ownAttrParams.value.spuImageList = photoList.value.map((item: any) => {
    return {
      imgName: item.name,
      //这里渲染的数据经过处理没事都是name➕url
      //但是经过upload组件上传的本地图片的url是本地的，他的在线地址在response的data上
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });

  await addAndUpdadteSPUProduct(ownAttrParams.value);
  if (ownAttrParams.value.id) {
    ElMessage({
      type: "success",
      message: "更新成功",
    });
  } else {
    ElMessage({
      type: "success",
      message: "添加成功",
    });
  }

  //传切换场景的数值
  //传是更新还是添加，更新是留在当前页，添加是返回在首页
  emit("updateScene", {
    val: 0,
    flag: ownAttrParams.value.id ? "更新" : "添加",
  });
};

//获取数据，显示在添加SPU的SPU品牌和SPU销售属性上
const getaddSPUTParamsFun = async (c3Id: number) => {
  //先清空残余数据
  resetAddSPUData();
  //获取SPU所有品牌数据
  const res1: SPUBrandList = await getSPUBrandList();
  //获取全部SPU销售属性
  const res4: AllSPUAttributeList = await getAllSPUAttributeAndValue();
  //存储SPU所有品牌
  getSPUBrandListRef.value = res1;
  //存储全部的SPU商品属性和属性值
  allAttributeAndValueList.value = res4;
  //三级分类ID
  ownAttrParams.value.category3Id = c3Id;
};
//清空添加SPU面板数值函数
const resetAddSPUData = () => {
  Object.assign(ownAttrParams.value, {
    id: "", //SPUid
    description: "", //描述
    spuName: "", //名字
    category3Id: "", //三级分类ID
    tmId: "", //品牌ID
    spuSaleAttrList: [], //没有需要接口获取
    spuImageList: [], //没有需要接口获取
  });
  //清空SPU所有品牌
  photoList.value = [];
  //清空已有的SPU商品属性和属性值
  attributeAndValueList.value = [];
};

//向外暴露方法，让父组件调用，方便在这里存数据
defineExpose({
  getAPI,
  getaddSPUTParamsFun,
});
</script>

<style scoped></style>
